<?php

///////
// IdleIRC 2020
// (C) Chris Dorman, GPLv3
// https://notabug.org/Pentium44/idleirc
///////

// Start session for username saves.
session_start();
include "config.php";

if(!file_exists("users"))
{
        mkdir("users", 0777);
}

function registerForm() {
    ?>
    <br>
    <div class="form">
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>?register=go" method="post">
		<table>

		<tr><td>Username:</td><td> <input style="padding: 2px; width: 300px;" class="text" type="text" name="username"></td></tr>
		<tr><td>Password:</td><td> <input style="padding: 2px; width: 300px;" class="text" type="password" name="password"></td></tr>
		<tr><td>Password again:</td><td> <input style="padding: 2px;width: 300px;" class="text" type="password" name="password-again"></td></tr>
	    <tr><td>Below forms:</td><td> The nickname form can be left blank and<br /> will be substituted with your username.</td></tr>
	    <tr><td>Default Nickname:</td><td> <input style="padding: 2px; width: 300px;" class="text" type="text" name="nick"></td></tr>
        <tr><td>Autoconnect/focus channel:</td><td> <input style="padding: 2px; width: 300px;" class="text" type="text" name="channel" value="<?php echo $GLOBALS['default_channel']; ?>"></td></tr>
<?php
    if($GLOBALS['allowMultiServer'] == "true") {
?>
    <tr><td>Server (IP:Port)</td><td> <input style="padding: 2px; width: 236px;" class="text" type="text" name="servaddr" value="<?php echo $GLOBALS['server']; ?>">:<input style="padding: 2px; width: 50px;" class="text" type="text" name="servport" value="<?php echo $GLOBALS['port']; ?>"></td></tr>
<?php
    }
?>
        </table>
        <br />
        <input style="padding: 2px;" class="text" type="submit" name="submitBtn" value="Create account">

        </form>
        </div>
        <br />
        <?php
}

function loginForm(){
?>
	<br>
	<div class="form">
		<p>
			<?php echo $GLOBALS['desc']; ?><br />
			Don't have an account? <a href="index.php?register">Create one</a> here!<br />
		</p>
		<form action="<?php echo $_SERVER['PHP_SELF']; ?>?do=login" method="post">
			<table>

			<tr><td>Username:</td><td> <input style="padding: 2px; width: 200px;" class="text" type="text" name="username"></td></tr>
			<tr><td>Password:</td><td> <input style="padding: 2px; width: 200px;" class="text" type="password" name="password"></td></tr>

			</table>
			<input style="padding: 2px;" class="text" type="submit" name="submitBtn" value="Login">
		</form>
	</div>
<?php
}

//Logout
if (isset($_GET['do']) && $_GET['do']=="logout") {
	$_SESSION['idleirc-user'] = null;
	$_SESSION['idleirc-channel'] = null;
}

if (isset($_GET['do']) && $_GET['do']=="settings") {
	$username = $_SESSION['idleirc-user'];
	$password = $_SESSION['idleirc-pass'];

	if (file_exists("users/$username.php")) {
                include("users/$username.php");
        } else {
                $userpass = "";
        }

        if (isset($_SESSION['idleirc-pass']) && $userpass != "" && $userpass == $_SESSION['idleirc-pass']) {
		if (isset($_POST['nick']) && $_POST['nick']!="") {
			file_put_contents("users/$username.php", "<?php \$usernickname='" . stripslashes(htmlentities($_POST['nick'])) . "'; ?>\n", FILE_APPEND);
			$_SESSION['idleirc-nick'] = stripslashes(htmlentities($_POST['nick']));
		}

		if (isset($_POST['channel']) && $_POST['channel']!="") {
			file_put_contents("users/$username.php", "<?php \$userchannel='" . stripslashes(htmlentities($_POST['channel'])) . "'; ?>\n", FILE_APPEND);
			$_SESSION['idleirc-channel'] = stripslashes(htmlentities($_POST['channel']));
		}

		if (isset($_POST['password']) && $_POST['password']!="") {
                        file_put_contents("users/$username.php", "<?php \$userpass='" . md5($_POST['password']) . "'; ?>\n", FILE_APPEND);
			$_SESSION['idleirc-pass'] = md5($_POST['password']);
                }

		if ($allowMultiServer == "true") {
			if (isset($_POST['servaddr']) && $_POST['servaddr']!="") {
				file_put_contents("users/$username.php", "<?php \$userserver='" . stripslashes(htmlentities($_POST['servaddr'])) . "'; ?>\n", FILE_APPEND);
				$_SESSION['idleirc-servaddr'] = stripslashes(htmlentities($_POST['servaddr']));
			}

			if (isset($_POST['servport']) && $_POST['servport']!="") {
				file_put_contents("users/$username.php", "<?php \$userserverport='" . stripslashes(htmlentities($_POST['servport'])) . "'; ?>\n", FILE_APPEND);
				$_SESSION['idleirc-servport'] = stripslashes(htmlentities($_POST['servport']));
			}
		}

		header("refresh: 0;url=index.php");
	} else {
		header("refresh: 0;url=index.php");
	}
}

if (isset($_GET['register']) && $_GET['register'] == "go") {
	if(isset($_POST['password']) && $_POST['password'] != "" && isset($_POST['password-again']) && $_POST['password-again'] != "" && $_POST['password'] == $_POST['password-again']) {
		if(isset($_POST['username']) && $_POST['username'] != "") {
			$username = stripslashes(htmlentities($_POST['username']));
			$password = md5($_POST['password']);
			$channame = isset($_POST['channel']) && ($_POST['channel'] !== "") ? htmlentities(stripslashes($_POST['channel'])) : $default_channel;
			$nickname = isset($_POST['nick']) && ($_POST['nick'] !== "") ? htmlentities(stripslashes($_POST['nick'])) : $username;
        		$servaddr = isset($_POST['servaddr']) && ($_POST['servaddr'] !== "") ? htmlentities(stripslashes($_POST['servaddr'])) : $server;
		        $servport = isset($_POST['servport']) && ($_POST['servport'] !== "") ? htmlentities(stripslashes($_POST['servport'])) : $port;
			file_put_contents("users/$username.php", "<?php \$userpass = '" . $password . "'; \$userchannel='" . $channame . "'; \$usernickname='" . $nickname . "'; \$userserver='" . $servaddr . "'; \$userserverport='" . $servport . "'; ?>\n");
			file_put_contents("users/.$username.first", "First time, start up\n");
			$_SESSION['idleirc-user'] = $username;
			$_SESSION['idleirc-nick'] = $nickname;
			$_SESSION['idleirc-pass'] = $password;
                        $_SESSION['idleirc-channel'] = $channame;
                        $_SESSION['idleirc-servaddr'] = $servaddr;
                        $_SESSION['idleirc-servport'] = $servport;
			header("refresh: 0;url=index.php");
		} else {
			echo "Please prove a username...";
		}
	} else {
		echo "ERROR: Passwords did not match...";
	}
}

// If web frontend is trying to login, process and connect
if (isset($_GET['do']) && $_GET['do']=="login" && isset($_POST['submitBtn']) && isset($_POST['password']) && $_POST['password']!=""){
	$name = isset($_POST['username']) && ($_POST['username'] !== "") && file_exists("users/" . $_POST['username'] . ".php") ? htmlentities(stripslashes($_POST['username'])) : "Unnamed";
	if(file_exists("users/$name.php")) {
		include("users/$name.php");
		if(md5($_POST['password']) == $userpass) {
			$_SESSION['idleirc-user'] = $name;
			$_SESSION['idleirc-nick'] = $usernickname;
			$_SESSION['idleirc-pass'] = $userpass;
			$_SESSION['idleirc-channel'] = $userchannel;
			$_SESSION['idleirc-servaddr'] = $userserver;
			$_SESSION['idleirc-servport'] = $userserverport;
			header("refresh: 0;url=index.php");
		} else {
			echo "ERROR: Failed to login: password incorrect.";
		}
	} else {
		echo "ERROR: Password for $name does not match";
	}
}

?>

<!DOCTYPE html>
<html>
<head>
   <title><?php echo $title . " " . $version; ?></title>
   <link href="<?php echo $ui_theme; ?>.css" rel="stylesheet" type="text/css" />
   <meta http-equiv="content-type" content="text/html; charset=utf-8">
   <meta name="description" content="<?php echo $desc; ?>" />
   <meta name="viewport" content="width=device-width, initial-scale=.5, shrink-to-fit=yes">
    <!--Needed for urls -->
    <script language="javascript" type="text/javascript">
        var nickName = "<?php echo $_SESSION['idleirc-user']; ?>";
    </script>
    <script language="javascript" type="text/javascript" src="core.js"></script>
    <script language="javascript" type="text/javascript">
<?php
if($hellFreezedOver == "yes") {
?>
    <!--
		var httpObject = null;
		var link = "";
        var link2 = "";
        var link3 = "";
		var pinglink = "";
        var ScrollDown = 0;
        var msgBox = document.getElementById('msgs');
        var userlist = document.getElementById('userlist');
		var timerID = 0;

		// Get the HTTP Object
		function getHTTPObject() {
			if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
			else if (window.XMLHttpRequest) return new XMLHttpRequest();
			else {
				alert("Your browser does not support AJAX.");
				return null;
			}
		}   

		// Change the value of the outputText field
		function setHtml() {
			if(ajaxVar.readyState == 4){
				var response = ajaxVar.responseText;
				var msgBox = document.getElementById("msgs");
				msgBox.innerHTML += response;
                ScrollDown = 0;
                MsgScrollDown();
			}
		}

		// Change the value of the outputText field
		function setAll() {
			if(ajaxVar.readyState == 4){
				var response = ajaxVar.responseText;
				var msgBox = document.getElementById("msgs");
                msgBox.innerHTML = response;
                ScrollDown = 0;
                MsgScrollDown();
			}
		}

        function doNotificationPm() {
            if(ajaxVar4.readyState == 4){
                var mentionUser = ajaxVar4.responseText;
                if(Notification.permission==="granted") {
                    var notify = new Notification("Private message from " + mentionUser, { body: ""});
                }
            }
        }

        function getPmUser() {
            ajaxVar4 = getHTTPObject();
            //var randomnumber=Math.floor(Math.random()*10000);
            if (ajaxVar4 != null) {
                link4 = "server.php?get=notificationpmed&nick="+nickName;
                ajaxVar4.open("GET", link4 , true);
                ajaxVar4.onreadystatechange = doNotificationPm;
                ajaxVar4.send(null);
            }
        }

        function checkNotificationPm() {
            if(ajaxVar5.readyState == 4){
                var returnMsg = ajaxVar5.responseText;
                var compareString = "true";
                //console.log(returnMsg);
                if(returnMsg.trim() === compareString.trim()) {
                    getPmUser();
                }
            }
        }

        function checkPmUrl() {
            ajaxVar5 = getHTTPObject();
            //var randomnumber=Math.floor(Math.random()*10000);
            if (ajaxVar5 != null) {
                link5 = "server.php?get=notificationpmedexists&nick="+nickName;
                ajaxVar5.open("GET", link5 , true);
                ajaxVar5.onreadystatechange = checkNotificationPm;
                ajaxVar5.send(null);
            }
        }


        function doNotificationMention() {
            if(ajaxVar2.readyState == 4){
                var mentionUser = ajaxVar2.responseText;
                if(Notification.permission==="granted") {
                    var notify = new Notification("You were mentioned by " + mentionUser, { body: ""});
                }
            }
        }

        function getMentionUser() {
            ajaxVar2 = getHTTPObject();
            //var randomnumber=Math.floor(Math.random()*10000);
            if (ajaxVar2 != null) {
                link2 = "server.php?get=notificationmention&nick="+nickName;
                ajaxVar2.open("GET", link2 , true);
                ajaxVar2.onreadystatechange = doNotificationMention;
                ajaxVar2.send(null);
            }
        }

        function checkNotificationMention() {
            if(ajaxVar3.readyState == 4){
                var returnMsg = ajaxVar3.responseText;
                var compareString = "true";
                //console.log(returnMsg);
                if(returnMsg.trim() === compareString.trim()) {
                    getMentionUser();
                }
            }
        }

        function checkMentionUrl() {
            ajaxVar3 = getHTTPObject();
            //var randomnumber=Math.floor(Math.random()*10000);
            if (ajaxVar3 != null) {
                link3 = "server.php?get=notificationmentionexists&nick="+nickName;
                ajaxVar3.open("GET", link3 , true);
                ajaxVar3.onreadystatechange = checkNotificationMention;
                ajaxVar3.send(null);
            }
        }

		// Implement business logic    
		function serverWrite() {    
			ajaxVar = getHTTPObject();
			if (ajaxVar != null) {
				link = "server.php?nick="+nickName+"&msg="+encodeURIComponent(document.getElementById('msg').value); 
				ajaxVar.open("GET", link , true);
				ajaxVar.send(null);
			}
		}

		// Implement business logic    
		function serverReload() {    
			ajaxVar = getHTTPObject();
			//var randomnumber=Math.floor(Math.random()*10000);
			if (ajaxVar != null) {
				link = "server.php?get&nick="+nickName;
				ajaxVar.open("GET", link , true);
				ajaxVar.onreadystatechange = setAll;
				ajaxVar.send(null);
			}
		}

        function MsgScrollDown() {
            if(ScrollDown != 1) {
                var msgBox = document.getElementById("msgs");
                msgBox.scrollTop = msgBox.scrollHeight;
                ScrollDown = 1;
            }
        }

		function UpdateTimer() {
			serverReload();
            MsgScrollDown();
            checkPmUrl();
            checkMentionUrl();
			setTimeout(UpdateTimer, 1000);
		}

		function doLogin() {
			ajaxVar = getHTTPObject();
			if(ajaxVar != null) {
				link = "server.php?do=login&nick="+nickName;
				ajaxVar.open("GET", link, true);
				ajaxVar.onreadystatechange = setHtml;
				ajaxVar.send(null);
				setTimeout(function() { window.location.reload(); },1000);
			}
		}

		function doClearLog() {
            ajaxVar = getHTTPObject();
            if(ajaxVar != null) {
                link = "server.php?do=clearlog&nick="+nickName;
                ajaxVar.open("GET", link, true);
                ajaxVar.onreadystatechange = setHtml;
                ajaxVar.send(null);
				setTimeout(function() { window.location.reload(); },1000);
            }
        }

		function doLogout() {
			ajaxVar = getHTTPObject();
			if(ajaxVar != null) {
				link = "server.php?do=logout&nick="+nickName;
				ajaxVar.open("GET", link, true);
				ajaxVar.onreadystatechange = setHtml;
				ajaxVar.send(null);
				setTimeout(function() { window.location.reload(); },1000);
			}
		}
		
		/*window.onbeforeunload = function (e) {
			doLogout();
		};*/
      
		function wrapBBCode(tag) {
			var msgInput = document.getElementById('msg');
			var content = msgInput.value;
			var selectedContent = content.substring(msgInput.selectionStart, msgInput.selectionEnd);
			var beforeContent = content.substring(0, msgInput.selectionStart);
			var afterContent = content.substring(msgInput.selectionEnd, content.length);
			msgInput.value = beforeContent + '[' + tag + ']' + selectedContent + '[/' + tag + ']' + afterContent;
		}

<?php
// Lets test this
}

if(file_exists("users/." . $_SESSION['idleirc-user'] . ".pingfile"))
{

?>

        function getInput() {
            // Send the server function the input
            var userInput = document.getElementById('msg');
            serverWrite(userInput.value);

            // Clean out the input values
            var msgBar = document.getElementById("msg");
            msgBar.value = "";
            msgBar.focus();
        }

        function keypressed(e) {
            if(e.keyCode=='13'){
                getInput();
            }
        }

        if(Notification.permission !== "granted") {
            Notification.requestPermission();
        }
<?php
} else {
?>

        function getInput() {
            // IRC bouncer not running, warn
            alert("You're not connected to the server, please connect your bouncer to send messages");
        }

        function keypressed(e) {
            if(e.keyCode=='13'){
                getInput();
            }
        }
<?php
}
?>
    //-->
    </script>   
</head>
<body <?php if(!isset($_GET['register']) && !isset($_GET['logs']) && !isset($_GET['settings']) && isset($_SESSION['idleirc-user']) && file_exists("users/." . $_SESSION['idleirc-user'] . ".pingfile")) { echo 'onload="UpdateTimer();"'; } ?>>

     <div class="info"><?php echo $pagetitle;
     if(isset($_SESSION['idleirc-user'])) { echo " ~ " . $_SESSION['idleirc-servaddr'] . ":" . $_SESSION['idleirc-servport'] . " on " . $_SESSION['idleirc-channel']; } ?></div>
<?php

if (isset($_GET['register'])) {
        registerForm();
}

if (!isset($_SESSION['idleirc-user'])) { 
    if(!isset($_GET['register'])) {
	    loginForm();
    }
} else if(isset($_GET['logs'])) {
	$username = $_SESSION['idleirc-user'];
	if(file_exists("users/$username.php")) { 
		include("users/$username.php");
	} else {
		$userpass = "";
	}

	if(isset($_SESSION['idleirc-pass']) && $userpass != "" && $userpass == $_SESSION['idleirc-pass']) {
		echo "<div class='navbar'><a href='index.php'>Back to IRC</a> &bull; <a onclick='doClearLog();'>Clear IRC logs</a>";

        if(file_exists("users/$username.logcount")) {
            echo "<br />Archived: ";
            $archivedLogCount = file_get_contents("users/$username.logcount");
            for($x = $archivedLogCount ; $x > 0 ; $x--) {
                echo "<a href='index.php?logs&page=$x'>$x</a>&nbsp;";
            }
        }

        echo "</div><br />\n";
        if(isset($_GET['page']) && $_GET['page']!="") {
            $logcontents = file_get_contents("users/$username." . $_GET['page'] . ".log");
            echo "<div id='logmsgs'><table>\n" . $logcontents . "</table></div>\n";
        } else {
            $logcontents = file_get_contents("users/$username.log");
    		echo "<div id='logmsgs'><table>\n" . $logcontents . "</table></div>\n";
        }
	}
} else if(isset($_GET['settings'])) {
        $username = $_SESSION['idleirc-user'];
        $logcontents = file_get_contents("users/$username.log");
        if(file_exists("users/$username.php")) {
                include("users/$username.php");
        } else {
                $userpass = "";
        }

        if(isset($_SESSION['idleirc-pass']) && $userpass != "" && $userpass == $_SESSION['idleirc-pass']) {
       		echo "<div class='navbar'><a href='index.php'>Back to IRC</a></div><br />\n";
       		?>

<br>
<div style="width: 500px; margin: 0 auto; text-align: center;">
	<p>Leave fields blank that you'd not like set. Fill in what you'd want to change and hit set. Settings will be saved and session will be updated</p>
	<form action="<?php echo $_SERVER['PHP_SELF']; ?>?do=settings" method="post">

	<table>
	<tr><td>Default Nickname: </td><td> <input style="padding: 2px; width: 300px;" class="text" type="text" name="nick"></td></tr>
	<tr><td>Autoconnect/focus channel: </td><td> <input style="padding: 2px; width: 300px;" class="text" type="text" name="channel" value="<?php echo $default_channel; ?>"></td></tr>
	<tr><td>New password: </td><td> <input style="padding: 2px; width: 300px;" class="text" type="password" name="password"></td></tr>
<?php
	if($allowMultiServer == "true") {
	?>	<tr><td>Server (IP:Port)</td><td> <input style="padding: 2px; width: 236px;" class="text" type="text" name="servaddr" value="<?php echo $server; ?>">:<input style="padding: 2px; width: 50px;" class="text" type="text" name="servport" value="<?php echo $port; ?>"></td></tr><?php
	}
?>
	</table>
	<input style="padding: 2px;" class="text" type="submit" name="submitBtn" value="Set">

	</form>
</div>


		<?php
        }
} else { 
    ?>
	<div class="navbar">
		<a href="index.php?do=logout">Logout</a>
        <?php

		// If this is the first login, make sure to start the bouncer! From there, the user will have toggle control.
		if (!file_exists("users/." . $_SESSION['idleirc-user'] . ".pingfile") && file_exists("users/."  . $_SESSION['idleirc-user'] . ".first")) {
			unlink("users/." . $_SESSION['idleirc-user'] . ".first");
			echo "<script language='javascript' type='text/javascript'>doLogin();</script>";
        }

        if (!file_exists("users/." . $_SESSION['idleirc-user'] . ".pingfile"))
        {
			echo "&bull;\n<a onclick='doLogin();'>Connect to server</a>\n";
		} else {
			echo "&bull;\n<a onclick='doLogout();'>Disconnect from server</a>\n";
		}
		?>
        &bull;
		<a href="index.php?logs">IRC Logs</a>
        &bull;
		<a href="index.php?settings">Settings</a>
	</div><br />
    <table class="clientcontain">
    <tr><td id="userlist">

    </td><td id="client">
		<div id="msgs">
		<?php 
			echo "<table>";
			$get = file_get_contents("users/" . $_SESSION['idleirc-user'] . ".log");
			echo $get;
			echo "</table>";
		?>
		</div>
		<div id="msgbox" onkeyup="keypressed(event);">
			<table>
				<tr>
					<td>
						<textarea name="msg" id="msg"></textarea>
					</td>
					<td>
						<button onclick="getInput();">Send</button>
					</td>
				</tr>
			</table>
		</div>
<?php            
    }

?>
    </td>
    </tr></table>
    
	<div id="footer">Powered by <a href='https://notabug.org/Pentium44/idleirc'><?php echo $title . " " . $version; ?></a></div>
    </div>
</body>   
</html>
